//The MIT License (MIT)
//
//Copyright (c) 2018 dote
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.github.dote.mio.client;


import com.github.dote.mio.ack.AckSendTask;
import com.github.dote.mio.client.callback.SendCallback;
import com.github.dote.mio.protocal.Packet;
import com.github.dote.mio.protocal.PacketFactory;
import com.github.dote.mio.protocal.PacketType;
import com.github.dote.mio.rtt.RTTHandler;
import com.github.dote.mio.util.ChannelUtil;
import com.github.dote.mio.util.CommonUtil;
import com.github.dote.mio.util.JsonUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class UdpClient implements IOClient {

    private AckSendTask ackSendTask;

    private Channel channel = null;
    private String sessionId = "";
    private String ip = "";
    private Map<String, Object> attrMap = new HashMap<>();

    private RTTHandler rttHandler = null;

    public UdpClient(AckSendTask ackSendTask, Channel channel) {
        this.ackSendTask = ackSendTask;
        this.channel = channel;
        this.ip = ChannelUtil.getIp(channel);
        this.sessionId = CommonUtil.createUniqueId();

    }


    @Override
    public String getSessionId() {
        return sessionId;
    }

    @Override
    public String getIp() {
        return ip;
    }

    @Override
    public void setAttr(String k, Object v) {
        if (attrMap.containsKey(k))
            attrMap.remove(k);
        attrMap.put(k, v);
    }

    @Override
    public boolean hasAttr(String k) {
        return attrMap.containsKey(k);
    }

    @Override
    public <T> T getAttr(String k) {
        return (T)attrMap.get(k);
    }

    @Override
    public <T> T getAttr(String k,Class<T> clazz) {
        Object obj=  attrMap.get(k);
        if(obj==null)
            return null;
        try {
            Method method = clazz.getMethod("valueOf",String.class);
            return (T) method.invoke(this,obj);
        } catch (Exception e) {
        }
        return (T)obj;
    }

    @Override
    public Map<String, Object> getAttrMap() {
        return attrMap;
    }

    @Override
    public void transfer(Packet packet, String toSessionId) {
        transfer(packet,toSessionId,null);
    }

    @Override
    public void transfer(Packet packet, String toSessionId, SendCallback sendCallback) {
        send(packet,toSessionId,sendCallback);
    }

    private void send(Packet packet, String toSessionId, SendCallback sendCallback) {
        if (channel != null) {
            if (isConnected()) {
                if (packet != null) {
                    final byte[] res = packet.toBytes();

                    final ByteBuf to = Unpooled.copiedBuffer(res);
                    ChannelFuture cf = channel.writeAndFlush(to);//.sync();

                    cf.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture future) {
                            if (future.isSuccess()) {
                                if (packet.isAck() && packet.getType() == PacketType.EVENT_MESSAGE)
                                    if (!ackSendTask.exist(packet.getAckId())) {
                                        if (toSessionId == null || "".equals(toSessionId)) {
                                            ackSendTask.put(UdpClient.this, packet, "0", UdpClient.this.sessionId);
                                        } else {
                                            ackSendTask.put(UdpClient.this, packet, packet.getSessionId(), toSessionId);
                                        }
                                    }
                            }
                            if (sendCallback != null) {
                                sendCallback.onSendResult(UdpClient.this, future.isSuccess());
                            }
                        }
                    });
                }
            }
        }
        if (sendCallback != null) {
            sendCallback.onSendResult(UdpClient.this, false);
        }
    }

    @Override
    public void send(Packet packet, SendCallback sendCallback) {
        send(packet,null,sendCallback);
    }


    @Override
    public void send(Packet packet) {
        send(packet, null);
    }

    @Override
    public void send(String eventName, String fromSessionId, Object data, boolean ack, SendCallback sendCallback) {
        Packet packet = PacketFactory.createEventPacket(eventName, fromSessionId, data, ack);
        send(packet, sendCallback);
    }

    @Override
    public void send(String eventName, String fromSessionId, Object data, SendCallback sendCallback) {
        send(eventName, fromSessionId, data, true, sendCallback);
    }

    @Override
    public void send(String eventName, String fromSessionId, Object data, boolean ack) {
        send(eventName, fromSessionId, data, ack, null);
    }

    @Override
    public void send(String eventName, String fromSessionId, Object data) {
        send(eventName, fromSessionId, data, true, null);
    }

    @Override
    public void send(String eventName, Object data) {
        send(eventName,"0",data);
    }

    @Override
    public void setRTTHandler(RTTHandler rttHandler) {
        this.rttHandler = rttHandler;
    }

    @Override
    public RTTHandler getRTTHandler() {
        return rttHandler;
    }

    @Override
    public boolean isConnected() {
        if (channel != null) {
            return channel.isActive();
        } else return false;
    }

    @Override
    public boolean close() {
        if (channel != null && isConnected()) {
            try {
                return channel.close().sync().isSuccess();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return false;
    }

    @Override
    public int compareTo(IOClient o) {
        long thisSessionId = Long.valueOf(this.sessionId);
        long oSessionId = Long.valueOf(o.getSessionId());
        return (int) (thisSessionId - oSessionId);
    }
}
